<!--
 * @Description: 
 * @Author: jiaxiuc
 * @Date: 2024-04-25
 * @LastEditors: jiaxiuc
 * @LastEditTime: 2024-04-25
-->
<template>
  <div class="page-wraper">
    <el-button type="primary" icon="el-icon-plus" @click="editBtn()">创建</el-button>
    <!-- <h5 class="page-title">巡检</h5> -->
    <el-table :data="tableData" border style="width: 100%; margin-top: 20px">
      <el-table-column prop="index" label="序号" width="80"> </el-table-column>
      <el-table-column prop="viewName" label="任务名称" width="200"> </el-table-column>
      <!-- <el-table-column prop="tableName" label="多维表格名称" width="200"> </el-table-column> -->
      <el-table-column prop="tableUrl" label="多维表格地址" width="250">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.tableUrl" placement="top">
            <el-link target="_blank" type="primary" class="column-hide" :href="scope.row.tableUrl">{{
              scope.row.tableUrl
            }}</el-link>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="viewTableName" label="多维表格数据表" width="200"> </el-table-column>
      <el-table-column prop="fieldList" label="表单字段" width="300">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.fields" placement="top">
            <span class="column-hide">{{ scope.row.fields }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="viewUrl" label="表单访问地址" width="250">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.viewUrl" placement="top">
            <el-link target="_blank" type="primary" class="column-hide" :href="scope.row.viewUrl">{{
              scope.row.viewUrl
            }}</el-link>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="editBtn(scope.row)">编辑</el-button>
          <el-button type="text" @click="delBtn(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <!-- <el-pagination background @size-change="pageSizeChange" @current-change="currentChange"
  :page-size="pageSize"
  layout="prev, pager, next"
  :total="totalCount">
</el-pagination> -->
    <!-- 弹窗修改 -->
    <el-dialog :title="form.id ? '编辑任务' : '创建任务'" :visible.sync="dialogFormVisible" width="600px">
      <el-form :model="form" label-width="120px" :rules="rules" ref="modalForm">
        <el-form-item label="任务名称" prop="viewName">
          <el-input v-model="form.viewName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="多维表格地址" prop="tableUrl">
          <el-input v-model="form.tableUrl" autocomplete="off" @change="getTableList"></el-input>
        </el-form-item>
        <el-form-item label="多维表格数据表" prop="viewTableToken">
          <el-select @change="tableChange" v-model="form.viewTableToken" placeholder="请选择数据表" filterable>
            <el-option
              v-for="(item, index) in tableList"
              :key="index"
              :label="item.name"
              :value="item.table_id"
            ></el-option>
          </el-select>
          <p class="desc">读取选中数据表中的所有字段信息（右侧两列根据字段类型配置进行显隐）</p>
        </el-form-item>
        <!-- <p class="desc"></p> -->
        <div class="field-list">
          <el-row type="flex" align="middle" v-for="(item, index) in form?.viewFields" :key="index">
            <el-col :span="5" class="field-name"> {{ item.field_name }} </el-col>
            <el-col :span="5">
              <el-switch
                @change="forceUpdate"
                active-text="启用"
                inactive-text="禁用"
                v-model="item.status"
              ></el-switch>
            </el-col>
            <template v-if="item.type == 3">
              <!-- <template v-if="item.type == 3 && (!item.property || item.property.options?.length == 0)"> -->
              <el-col :span="6" :offset="1">
                <el-select
                  size="small"
                  clearable
                  filterable
                  placeholder="关联数据表"
                  v-model="item.tableId"
                  @change="getTableField(item)"
                >
                  <el-option
                    v-for="(item, index2) in tableList"
                    :key="index2"
                    :label="item.name"
                    :value="item.table_id"
                  ></el-option>
                </el-select>
              </el-col>

              <el-col :span="6" :offset="1">
                <el-select
                  clearable
                  filterable
                  size="small"
                  @change="forceUpdate"
                  placeholder="关联字段"
                  v-model="item.fieldName"
                >
                  <el-option
                    v-for="(item, index) in item.tableId && tableFieIdsObj[item.tableId]"
                    :key="index"
                    :label="item.field_name"
                    :value="item.field_name"
                  ></el-option>
                </el-select>
              </el-col>
            </template>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button :loading="submiting" type="primary" @click="submitBtn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { adminService } from '@/api'
export default {
  name: 'Config',
  data() {
    return {
      loading: false,
      submiting: false,
      tableFieIdsObj: {},
      tableData: [],
      //pageSize: 20,
      //totalCount: 100,
      dialogFormVisible: false,
      form: {
        name: '',
      },
      rules: {
        viewName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        tableUrl: [{ required: true, message: '请输入表格地址', trigger: 'blur' }],
        viewTableToken: [{ required: true, message: '请选择多维表格数据表', trigger: 'blur' }],
      },
      tableList: [],
    }
  },
  async created() {
    this.loadData()
  },
  //方法
  methods: {
    async loadData() {
      const res = await adminService.selectViewConfig()
      this.tableData = res.result.map((record, index) => {
        const fields = record.viewFieldList
          .filter((item) => item.status == 1)
          .map((item) => {
            return item.feishuFieldName
          })
          .join(',')
        return { ...record.viewConfig, fields, viewFieldList: record.viewFieldList, index: index + 1 }
      })
      this.$forceUpdate()
    },
    editBtn(data) {
      this.tableFieIdsObj = {}
      if (data) {
        this.showLoading()
        this.form = JSON.parse(JSON.stringify(data))
        this.resetFormData(data)
      } else {
        this.form = {}
      }
      this.dialogFormVisible = true
      this.tableList = []
      this.getTableList()
      this.$refs.modalForm.resetFields()
      //   data.viewFieldList?.forEach((record) => {
      //       record.fieIdExt = record.fieIdExt ? JSON.parse(record.fieIdExt) : {}
      //       record.status = record.status == 1 ? true : false
      //     })
    },
    delBtn(data) {
      console.log(data)
      this.$confirm('此操作将删除该巡检任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        adminService.deleteViewConfig({ id: data.id }).then((res) => {
          if (res.result) {
            this.$message({
              type: 'success',
              message: '删除成功!',
            })
            this.loadData()
          } else {
            this.$message({
              type: 'error',
              message: res?.error?.msg || '删除失败!',
            })
          }
        })
      })
    },
    forceUpdate() {
      this.$forceUpdate()
    },
    async tableChange(tableId) {
      this.showLoading()
      if (!this.tableFieIdsObj[tableId]) {
        const res = await adminService.showTableFields({
          tableUrl: this.form.tableUrl,
          tableId: tableId,
        })
        this.tableFieIdsObj[tableId] = res.result
      }
      this.form.viewTableName = this.tableList.find((item) => item.table_id == tableId)?.name || ''
      this.form.viewFields = this.tableFieIdsObj[tableId].map((record) => {
        record.status = false
        record.fieIdExt = {}
        return record
      })
      this.$forceUpdate()
      this.$nextTick(() => {
        this.hideLoading()
      })
    },
    async getTableList() {
      if (!this.form.tableUrl) return false
      this.form.appToken = this.form.tableUrl.split('/').pop().split('?')[0]
      const res = await adminService.showTable({ tableUrl: this.form.tableUrl })
      this.tableList = res.result.map((record) => {
        return record
      })
    },
    async resetFormData(data) {
      const tableIds = [data.viewTableToken]
      data.viewFieldList?.forEach((item) => {
        if (item.fieIdExt) {
          const fieIdExt = JSON.parse(item.fieIdExt)
          if (fieIdExt?.tableId) {
            tableIds.push(fieIdExt.tableId)
          }
        }
      })

      for (let i = 0; i < tableIds.length; i++) {
        const res = await adminService.showTableFields({
          tableUrl: this.form.tableUrl,
          tableId: tableIds[i],
        })
        this.tableFieIdsObj[tableIds[i]] = res.result
      }
      this.form.viewFields = this.tableFieIdsObj[data.viewTableToken].map((record) => {
        const field =
          this.form.viewFieldList.find((item) => {
            return item.feishuFieldName == record.field_name
          }) || {}
        record.fieIdExt = {}
        if (field?.fieIdExt && typeof field?.fieIdExt == 'string') {
          record.fieIdExt = JSON.parse(field?.fieIdExt)
          record.tableId = record.fieIdExt.tableId || ''
          record.fieldName = record.fieIdExt.fieldName || ''
          record.appToken = record.fieIdExt.appToken || ''
        }
        console.info(record.field_name, field, 112233)
        record.id = field?.id || ''
        record.status = field?.status == 1 ? true : false
        return record
      })
      this.$forceUpdate()
      this.$nextTick(() => {
        this.hideLoading()
      })
    },
    async getTableField(data) {
      const tableId = data.tableId
      data.fieldName = ''
      if (this.tableFieIdsObj[tableId] || !tableId) {
        return this.$forceUpdate()
      }
      const res = await adminService.showTableFields({
        tableUrl: this.form.tableUrl,
        tableId: tableId,
      })
      this.tableFieIdsObj[tableId] = res.result
      this.$forceUpdate()
    },
    submitBtn() {
      this.$refs.modalForm.validate(async (valid) => {
        if (!valid) {
          return console.log('error submit!!')
        } else {
          this.submitData()
        }
      })
    },
    async submitData() {
      this.submiting = true
      const params = JSON.parse(JSON.stringify(this.form))
      delete params.viewFieldList
      let errorMsg = ''
      params.viewFields = params.viewFields.map((record) => {
        record.status = record.status ? 1 : 0
        if (record.type == 3) {
          //const options = record?.property?.options || []
          if (record.fieldName) {
            record.fieIdExt = JSON.stringify({
              tableId: record.tableId,
              fieldName: record.fieldName,
              appToken: record.appToken || params.appToken,
            })
          } /* else if (options.length == 0) {
            errorMsg = `“${record.field_name}”是引用类型，请填写引用表格信息`
          }*/ else {
            record.fieIdExt = JSON.stringify({ fieldName: record.field_name, tableId: '', appToken: '' })
          }
        } else if (record.type == 11) {
          record.fieIdExt = JSON.stringify([{ id: '', name: '' }])
        } else if (record.type == 15) {
          record.fieIdExt = JSON.stringify([{ text: '图片', link: '' }])
        } else {
          record.fieIdExt = ''
        }
        //设置提交字段
        record.feishuFieldName = record.field_name
        record.fieldType = record.type
        return record
      })
      if (errorMsg) {
        this.submiting = false
        return this.$message.error(errorMsg)
      }
      const res = await adminService.addTableView(params)
      if (res.result) {
        this.$message.success(params.id ? '编辑成功' : '添加成功')
        this.loadData()
        this.dialogFormVisible = false
      } else {
        this.$message.error(res?.error?.msg)
      }
      this.submiting = false
    },
    showLoading() {
      this.loading = this.$loading({
        target: '.el-dialog',
        text: '加载中……',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.7)',
      })
    },
    hideLoading() {
      this.loading.close()
    },
    pageSizeChange() {},
    currentChange() {},
  },
}
</script>
<style lang="less" scoped>
.field-list {
  margin-top: 20px;
  /deep/ .el-row {
    margin-bottom: 16px;
  }
  .field-name {
    font-size: 14px;
  }
}
.desc {
  color: #767676;
  font-size: 12px;
}
</style>
